<template><!--分享-->
    <div style="height:100%;position: relative;overflow: hidden;">
        <div style="height: 100%;overflow: auto;">
            <navbar :title="$t('knowledge_share_add') + shareType" :showBackButton=false :showLeftArrow=false>
                <template #left>
                    <span class="iconfont icon-cha head-left" @click="back()"></span>
                </template>
                <template #right>
                    <span @click="beforeSave" class="font-size15 write-btn-right head-right" v-if="(($route.query.type != 'ARTICLE' && (kbi_title == '' || upFiles.length == 0)) || ($route.query.type == 'ARTICLE' && (kbi_title == '' || content.replace(/(^\s*)|(\s*$)/g, '') == '' || errors.has('tipsContent')))) || !selectCatalog || errors.has('tipsTitle') || errors.has('tipsDetail') || kbi_title.replace(/(^\s*)|(\s*$)/g, '') == ''">{{ $t("knowledge_share_add") }}</span>
                    <span class="font-size15 write-btn-right head-right cur" @click="save" v-if="(($route.query.type != 'ARTICLE' && kbi_title != '' && upFiles.length != 0) || ($route.query.type == 'ARTICLE' && kbi_title != '' && content.replace(/(^\s*)|(\s*$)/g, '') !== '' && !errors.has('tipsContent'))) && selectCatalog && !errors.has('tipsTitle') && !errors.has('tipsDetail') && kbi_title.replace(/(^\s*)|(\s*$)/g, '') !== ''">{{ $t("knowledge_share_add") }}</span>
                </template>
            </navbar>
            <div class="content-noBottom">
                <div class="layer-content-box">
                    <div class="add-contents-box">
                        <p class="word-title-06">{{ $t("knowledge_share_title") }}</p><!--标题(必填)-->
                        <div class="white-bg bottom-shadow">
                            <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_1')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'ARTICLE'"></textarea><!--输入文章标题...-->
                            <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_2')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'DOCUMENT'"></textarea><!--输入文档标题...-->
                            <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_3')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'IMAGE'"></textarea><!--输入图片标题...-->
                            <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_4')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'VEDIO'"></textarea><!--输入视频标题...-->
                            <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_5')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'FILES'"></textarea><!--输入文件标题...-->
                            <p  class="font-size11 colorfd3 warning-red-tan warning" v-if="errors.has('tipsTitle')">{{ $t("exceeded_word_range_tips", {'value': '40'}) }}</p><!--40-->
                        </div>
<!--                        <p class="word-title-06">{{ $t("mod_desc") }}</p>&lt;!&ndash;简介&ndash;&gt;-->
<!--                        <div class="white-bg">-->
<!--                            <textarea v-validate="'tipsDetail'" name="tipsDetail" v-model="kbi_desc" :placeholder="$t('knowledge_share_desc_tips_1')" style="height: 60px;" v-if="$route.query.type == 'ARTICLE'"></textarea>&lt;!&ndash;输入文章简介...&ndash;&gt;-->
<!--                            <textarea v-validate="'tipsDetail'" name="tipsDetail" v-model="kbi_desc" :placeholder="$t('knowledge_share_desc_tips_2')" style="height: 60px;" v-if="$route.query.type == 'DOCUMENT'"></textarea>&lt;!&ndash;输入文档简介...&ndash;&gt;-->
<!--                            <textarea v-validate="'tipsDetail'" name="tipsDetail" v-model="kbi_desc" :placeholder="$t('knowledge_share_desc_tips_3')" style="height: 60px;" v-if="$route.query.type == 'IMAGE'"></textarea>&lt;!&ndash;输入图片简介...&ndash;&gt;-->
<!--                            <textarea v-validate="'tipsDetail'" name="tipsDetail" v-model="kbi_desc" :placeholder="$t('knowledge_share_desc_tips_4')" style="height: 60px;" v-if="$route.query.type == 'VEDIO'"></textarea>&lt;!&ndash;输入视频简介...&ndash;&gt;-->
<!--                            <p class="font-size11 colorfd3 warning-red-tan warning" v-if="errors.has('tipsDetail')">{{ $t("exceeded_word_range_tips", {'value': '200'}) }}</p>&lt;!&ndash;200&ndash;&gt;-->
<!--                        </div>-->
                        <!--文章内容-->
                        <div v-if="$route.query.type === 'ARTICLE'">
                            <p class="word-title-06">{{ $t("knowledge_share_content") }}</p><!--内容(必填)-->
                            <div class="white-bg">
<!--                                <textarea v-validate="'tipsContent'" name="tipsContent" v-model="content" :placeholder="$t('knowledge_share_content_tips_art')"></textarea>&lt;!&ndash;输入文章内容...&ndash;&gt;-->
                                <div>
                                    <quill-editor
                                        style="height: 300px"
                                        ref="myQuillEditor"
                                        v-model="content"
                                        :options="editorOption"
                                        @change="onEditorChange"
                                    />
                                </div>
                                <p class="font-size11 colorfd3 warning-red-tan warning" v-if="errors.has('tipsContent')">{{ $t("exceeded_word_range_tips", {'value': '10000'}) }}</p><!--10000-->
                            </div>
                        </div>
                        <!--添加图片-->
<!--                        <div class="border-top2 bottom-shadow white-bg module-box-18 clearfix" v-if="$route.query.type == 'IMAGE'">-->
<!--                            <div class="module-img-box" style="margin-top: 20px;" v-if="upFiles.length == 0">-->
<!--                                <div class="box-table" style="height: 70px;">-->
<!--                                    <div class="box-table-cell">-->
<!--                                        <p class="color999 font-size13">{{ $t("lab_file_tips_8") }}</p>&lt;!&ndash;注：支持jpg、jpeg、gif、png格式的文件&ndash;&gt;-->
<!--                                    </div>-->
<!--                                </div>-->
<!--                            </div>-->
<!--                            <label class="add-icon-box-02" style="float: right; margin-right: -85px;">-->
<!--                                <input type="file" @change="shareUpFile" hidden>-->
<!--                                <span class="add-icon-02"></span>-->
<!--                            </label>-->
<!--                            &lt;!&ndash;添加图片后&ndash;&gt;-->
<!--                            <div class="module-img-box">-->
<!--                                <div class="img-box-2" v-for="(item, index) in upFiles" :key="index">-->
<!--                                    <img :src="appUrl + item.kba_url" alt="" style="width: 100%;height: 100%;" :preview="index"/>-->
<!--                                    <em @click="deleteUpFile(index, item.kba_id)" class="img-delete" ></em>-->
<!--                                </div>-->
<!--                            </div>-->
<!--                        </div>-->
                        <div class="border-top2 bottom-shadow white-bg module-box-18 clearfix" :style="{'padding-right' :upFiles.length !== 0 ? '15px' : '100px'}" v-if="$route.query.type !== 'ARTICLE' && $route.query.type !== 'IMAGE'">
                            <!--添加文档、视频的提示-->
                            <div v-if="upFiles.length == 0">
                                <div class="module-img-box" style="margin-top: 20px;">
                                    <div class="box-table" style="height: 70px;">
                                        <p class="color999 box-table-cell" v-if="$route.query.type == 'DOCUMENT'">{{ $t("lab_file_tips_9") }}</p><!--注：支持doc、docx、xls、xlsx、ppt、pdf格式的文件-->
                                        <p class="color999 box-table-cell" v-if="$route.query.type == 'VEDIO'">{{ $t("lab_file_tips_10") }}</p><!--注：支持MP4格式的文件-->
                                        <p class="color999 box-table-cell" v-if="$route.query.type == 'FILES'">{{ $t("lab_file_tips_15") }}</p><!--注：支持doc、docx、xls、xlsx、ppt、pdf、txt、mp4、avi、flv、mov、3gp和mp3格式-->
                                    </div>
                                </div>
                                <label class="add-icon-box-02" style="float: right; margin-right: -85px;">
                                    <input type="file" @change="shareUpFile" hidden>
                                    <span class="add-icon-02"></span>
                                </label>
                            </div>
                            <!--文件上传后-->
                            <ul class="upload-doc">
                                <li v-for="(item, index) in upFiles" :key="index">
                                    <div  class="other-upFile-style">
                                        <div style="margin-right: 5px;">
                                            <i class="link-document"></i>
                                        </div>
                                        <div>
<!--                                            <span>{{ item.kba_filename | omit( item.kba_file.split('.')[1] ) }}</span>-->
                                            <span>{{ item.orignalFileName }}</span>
                                        </div>
<!--                                        <i class="icon-delete-file" @click="deleteUpFile(index, item.kba_id)"></i>-->
                                        <i class="icon-delete-file" @click="deleteUpFile(index)"></i>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="margin-top10">
                        <ul class="module-list-10">
                            <li class="clearfix" @click="tagSelect('classify')">
                                <span class="font-size15">{{ $t("knowledge_share_cat") }}</span><!--分类(必选)-->
                                <i class="arrow-right"></i>
                                <span class="color999 word-title-08">
                                    <em v-if="selectCatalog">{{selectCatalog.kbcTitle}}</em>
                                </span>
                            </li>
                            <li class="clearfix" @click="tagSelect('source')">
                                <span class="font-size15">{{ $t('kbi_source') }}</span>
                                <i class="arrow-right"></i>
                                <span class="color999 word-title-08">
                                    <span>{{ kbiDocumentSourceType === 0 ? $t('circle_kg_47') : $t('kbi_zhuanzai') }}</span>
                                </span>
                            </li>
                            <li class="clearfix" v-show="$route.query.type == 'DOCUMENT' || $route.query.type == 'FILES'">
                                <span class="font-size15">{{ $t('kbi_is_down') }}</span>
                                <span class="color999 word-title-08">
                                    <input type="checkbox" name="isDown" v-model="isDown" style="width: 18px;height: 18px;"/>
                                </span>
                            </li>
                            <li class="clearfix" @click="tipSelectType = 1">
                                <span class="font-size15">{{ $t('kbi_access_qx') }}</span>
                                <i class="arrow-right"></i>
                                <span class="color999 word-title-08">
                                    <span v-if="kbiAccessType === 0">{{ $t('kbi_open') }}</span>
                                    <span v-else-if="kbiAccessType === 2">{{ $t('kbi_my_access') }}</span>
                                    <span v-else>{{ $t('kbi_access_select_user',{'value': kbiAccessPersonnelIds.length}) }}</span>
                                </span>
                            </li>
                            <li class="clearfix" @click="() => {if (kbiAccessType !== 2) {tipSelectType = 2}}">
                                <span class="font-size15">{{ $t('kbi_edit_qx') }}</span>
                                <i class="arrow-right"></i>
                                <span class="color999 word-title-08">
                                    <span v-if="kbiAccessType === 2">{{ $t('kbi_my_edit') }}</span>
                                    <span v-else-if="kbiEditType === 1">{{ $t('kbi_my_edit') }}</span>
                                    <span v-else>{{ $t('kbi_edit_select_user',{'value': kbiEditPersonnelIds.length}) }}</span>
                                </span>
                            </li>
<!--                            <li class="clearfix" @click="tagSelect('tag')">-->
<!--                                <span class="font-size15">{{ $t("knowledge_lab") }}</span>&lt;!&ndash;标签&ndash;&gt;-->
<!--                                <i class="arrow-right"></i>-->
<!--                                <span class="color999 word-title-08">-->
<!--                                    <em v-for="(item, index) in labelList" :key="index">{{item.tag_title}}<i v-if="labelList.length -1 != index">,</i></em>-->
<!--                                </span>-->
<!--                            </li>-->
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="popup-box" v-if="tagToggle">
            <div style="height: 100%;overflow: auto;">
                <!--分类-->
                <div v-if="toggleType === 'source'">
                    <div class="layer-header-box white-bg">
                        <span class="icon-back-layer" @click="closeLayer"></span>
                            {{ $t("kbi_source") }}
                        <span style="color: #333" class="font-size15 write-btn-right cur" @click="sourceSave">{{ $t("save") }}</span><!--保存-->
                    </div>
                    <div style="padding: 30px 15px">
                        <div style="width: 100%;margin-bottom: 15px;" @click="kbSourceType = 0">
                            <div style="width: 100%;"><input type="radio" name="source" :value="0" style="margin-right: 5px" v-model="kbSourceType">{{ $t('kbi_yuanchuang') }}</div>
                        </div>
                        <div @click="kbSourceType = 1">
                            <div style="width: 100%;"><input type="radio" name="source" :value="1" style="margin-right: 5px" v-model="kbSourceType">{{ $t('kbi_zhuanzai') }}</div>
                            <div style="width: 100%;margin-top: 10px" v-if="kbSourceType === 1"><input type="text" style="width: 80%;height: 20px;" v-model="kbiDocumentSourceUrl"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="saving-box" v-if="uploading">
            <p>
                <van-loading type="spinner" size="24" />
            </p>
            <p>{{ $t('uploading') }}</p><!--上传中-->
        </div>
        <!--tip-->
        <van-dialog
        v-model="leaveHint"
        show-cancel-button
        :title="$t('confirm_exit_1')"
        :message="$t('confirm_exit_content_1')"
        :cancelButtonText="$t('cancel')"
        :confirm-button-text="$t('sure')"
        @confirm="$router.go(-1)"
        >
        </van-dialog>
        <div class="toast-box-03" v-if="fileTip">
            <p class="toast-box-03-title">{{ msg }}</p>
        </div>
        <input style="position: fixed;left: -2000px;top: -2000px;" @change="handleAdd_quill_editor" id="input_hide"
               class="upload_input" type="file">
        <div style="width: 100%;height: 100%;z-index: 998;position: absolute;background: rgba(0,0,0,0.5);top: 0" v-if="tipSelectType === 1" @click="tipSelectType = 0">
            <div style="position: absolute;bottom: 0;z-index: 999;background: #fff;left: 0;width: 100%">
                <div style="line-height: 50px;font-size: 16px;text-align: center" @click="kbiAccessType = 0">{{ $t('kbi_open') }}</div>
                <div style="line-height: 50px;font-size: 16px;text-align: center;border-top: 1px solid #ccc" @click="kbiAccessType = 2">{{ $t('kbi_my_access') }}</div>
                <div style="line-height: 50px;font-size: 16px;text-align: center;border-top: 1px solid #ccc" @click="tagSelect('access')">{{ $t('kbi_you_access') }}</div>
            </div>
        </div>
        <div style="width: 100%;height: 100%;z-index: 998;position: absolute;background: rgba(0,0,0,0.5);top: 0" v-if="tipSelectType === 2" @click="tipSelectType = 0">
            <div style="position: absolute;bottom: 0;z-index: 999;background: #fff;left: 0;width: 100%">
                <div style="line-height: 50px;font-size: 16px;text-align: center" @click="kbiEditType = 1">{{ $t('kbi_my_edit') }}</div>
                <div style="line-height: 50px;font-size: 16px;text-align: center;border-top: 1px solid #ccc" @click="tagSelect('edit')">{{ $t('kbi_you_edit') }}</div>
            </div>
        </div>
        <new-select-user :is-show.sync="isAccess" :default-selected-id-list="kbiAccessPersonnelIds" @changeObjList="accessMemberSelect" @changeIdList="(ids)=> {kbiAccessPersonnelIds = ids}"></new-select-user>
        <new-select-user v-if="kbiAccessType === 0" :is-show.sync="isEdit" :default-selected-id-list="kbiEditPersonnelIds" @changeIdList="(ids)=> {kbiEditPersonnelIds = ids}"></new-select-user>
        <scope-select-user v-else :is-show.sync="isEdit" :scope-user-list="selectAccessObjs" :default-selected-id-list="kbiEditPersonnelIds" @changeIdList="(ids)=> {kbiEditPersonnelIds = ids}"></scope-select-user>
        <!-- 分类目录弹出层 -->
        <div>
            <van-popup
                v-model="show"
                round
                position="bottom">
                <van-cascader
                    v-model="cascaderValue"
                    :title="$t('circle_kg_58')"
                    active-color="#075ebb"
                    :options="getClassifyList"
                    @close="show = false"
                    @change="mlChange"
                    :field-names="{text: 'name', value: 'id', children: 'children'}"
                    />
            </van-popup>
        </div>
    </div>
</template>

<script>
import { Cascader, Popup } from 'vant';
import SelectUser from './SelectUser';
import {appUrl} from '../../../config/loginConfig';
import NewSelectUser from '../common/NewSelectUser';
import ScopeSelectUser from '../common/ScopeSelectUser';
export default {
    name: 'AddShare',
    components: {
        ScopeSelectUser,
        NewSelectUser,
        SelectUser,
        vanCascader: Cascader,
        vanPopup: Popup
    },
    data() {
        return {
            handleContent: '',
            shareType: '',
            tagToggle: false,
            getClassifyList: [], //分类
            getTagList: [], //标签
            upFiles: [],
            kbi_title: '',
            kbi_desc: '',
            catalogSelected: [],
            tagsSelected: [],
            content: '',
            fileTip: false,
            classificationList: [],
            labelList: [],
            uploading: false,
            leaveHint: false, //离开提示
            msg: '',
            getTwoClassList: [],
            getThreeClassList: [],
            selectCatalog: null,
            tempSelectCatalog: null,
            editorOption: {
                modules: {
                    toolbar: {
                        container: [
                            ['bold', 'italic'], // 加粗 斜体 下划线
                            [{ header: 1 }, { header: 2 }], // 1、2 级标题
                            ['image'] // 链接、图片、视频
                        ], //工具菜单栏配置
                        handlers: {
                            'image': function(value) {
                                if (value) {
                                    document.querySelector('#input_hide').click();
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    }
                },
                placeholder: this.$t('knowledge_share_content_tips_art'), //提示
                readyOnly: false, //是否只读
                theme: 'snow', //主题 snow/bubble
                syntax: true //语法检测
            },
            isDown: true, //是否允许下载
            kbiDocumentSourceType: 0, //知识文档来源
            kbiDocumentSourceUrl: '', //来源url
            kbSourceType: 0, //知识文档来源
            tipSelectType: 0,
            kbiAccessType: 0,
            kbiEditType: 1,
            kbiAccessPersonnelIds: [],
            kbiEditPersonnelIds: [],
            isAccess: false,
            isEdit: false,
            selectAccessObjs: [],
            show: false, // 目录弹窗
            cascaderValue: ''
        };
    },
    methods: {
        accessMemberSelect(objs) {
            if (this.kbiEditPersonnelIds && this.kbiEditPersonnelIds.length > 0) {
                if (objs && objs.length > 0) {
                    let exitsIds = [];
                    objs.forEach(item => {
                        if (this.kbiEditPersonnelIds.indexOf(item.id) > -1) {
                            exitsIds.push(item.id);
                        }
                    });
                    if (exitsIds.length === 0) {
                        this.kbiEditType = 1;
                    }
                    this.kbiEditPersonnelIds = exitsIds;
                }
            }
            this.selectAccessObjs = objs;
        },
        handleAdd_quill_editor(ev) { // 上传富文本
            const extension = ev.target.files[0].name.split('.').pop().toLowerCase();
            const imageExtensions = ['JPEG', 'JPG', 'GIF', 'PNG', 'jpeg', 'jpg', 'gif', 'png'];
            let isImage = imageExtensions.includes(extension);
            if (!isImage) {
                this.$toast(this.$t('lab_file_tips_6'));
                return false;
            }
            let vm = this;
            let files = ev.target.files[0];
            let param = new FormData(); // 创建form对象
            param.append('file', files); // 通过append向form对象添加数据
            let config = {
                headers: {'Content-Type': 'multipart/form-data'}
            }; // 添加请求头
            this.$axios.post(`/app/api/file/editor`, param, config).then(response => {
                if (response.data.message === 'SUCCESS') {
                    let quillFwb = vm.$refs['myQuillEditor'].quill;
                    // 获取光标所在位置
                    let length = quillFwb.getSelection().index;
                    // 插入图片，res为服务器返回的图片链接地址
                    // eslint-disable-next-line no-undef
                    quillFwb.insertEmbed(length, 'image', response.data.url);
                    // 调整光标到最后
                    quillFwb.setSelection(length + 1);
                }
            });
        },
        onEditorChange({ quill, html, text }) {
            this.content = html;
            if (process.env.NODE_ENV === 'production_app') {
                this.handleContent = html.split(this.$store.getters.getAppUrl).join('');
            }
        },
        findChildClass(data, level) {
            if (this.tempSelectCatalog && this.tempSelectCatalog.kbcId === data.kbcId) {
                this.tempSelectCatalog = null;
            } else {
                if (level === 1) {
                    this.getTwoClassList = [];
                    this.getThreeClassList = [];
                }
                if (level === 2) {
                    this.getThreeClassList = [];
                }
                if (level === 3) {
                    this.tempSelectCatalog = data;
                    return;
                }
                this.tempSelectCatalog = data;
                this.findClassCatalog(data.kbcId, level);
            }
        },
        //退出当前页面，如果填写了信息，提示弹出层，否则直接返回上一个页面
        back() {
            if (this.$route.query.type === 'IMAGE' || this.$route.query.type === 'VEDIO' || this.$route.query.type === 'DOCUMENT' || this.$route.query.type === 'FILES') { //图片
                if (this.kbi_title === '' && this.kbi_desc === '' && this.upFiles.length === 0 && this.classificationList.length === 0 && this.labelList.length === 0) {
                    this.$router.go(-1);
                } else {
                    this.leaveHint = true;
                }
            } else { //文章
                if (this.kbi_title === '' && this.kbi_desc === '' && this.content === '' && this.upFiles.length === 0 && this.classificationList.length === 0 && this.labelList.length === 0) {
                    this.$router.go(-1);
                } else {
                    this.leaveHint = true;
                }
            }
        },
        tagSelect(toggleType) {
            this.tagToggle = true;
            switch (toggleType) {
            case 'classify':
                this.toggleType = 'classify';
                this.catalogSelected = this.classificationList;
                this.tagToggle = false;
                this.show = true;
                break;
            case 'tag':
                this.toggleType = 'tag'; //已审批
                this.tagsSelected = this.labelList;
                break;
            case 'source':
                this.toggleType = 'source';
                this.kbSourceType = this.kbiDocumentSourceType;
                break;
            case 'access':
                this.toggleType = 'access';
                this.isAccess = true;
                break;
            case 'edit':
                this.toggleType = 'edit';
                this.isEdit = true;
                break;
            };
        },
        closeLayer(event) {
            this.kbSourceType = 0;
            // this.kbiDocumentSourceType = 0;
            this.tagToggle = false;
        },
        sourceSave() {
            if (this.kbSourceType === 1 && this.kbiDocumentSourceUrl.length > 0 && this.kbiDocumentSourceUrl.toLowerCase().indexOf('http://') === -1 && this.kbiDocumentSourceUrl.toLowerCase().indexOf('https://') === -1) {
                this.kbiDocumentSourceUrl = '';
                this.$toast(this.$t('out_link_tip'));
                return;
            }
            this.kbiDocumentSourceType = this.kbSourceType;
            this.closeLayer();
        },
        arrayToString(arr, key, spit) {
            let str = [];
            if (arr && arr.length > 0) {
                for (let item of arr) {
                    str.push(item[key]);
                }
            }
            return str.join(spit);
        },
        validataFile(file, uploadType) {
            if (!file || file === '' || !uploadType || uploadType === '') { return false; };
            var fileType = file.substring(file.lastIndexOf('.') + 1);
            var checkType = '';
            switch (uploadType) {
            case 'IMAGE' :
                checkType = 'jpg-jpeg-gif-png-JPG-JPEG-GIF-PNG';
                break;
            case 'DOCUMENT' :
                checkType = 'doc-docx-xls-xlsx-ppt-pptx-pdt-pdf-DOC-DOCX-XLS-XLSX-PPT-PPTX-PDT-PDF';
                break;
            case 'VEDIO' :
                checkType = 'mp4-MP4-mov-MOV';
                break;
            case 'FILES':
                checkType = `doc-docx-xls-xlsx-ppt-pptx-pdt-pdf-txt-
                DOC-DOCX-XLS-XLSX-PPT-PPTX-PDT-PDF-TXT-
                mp4-avi-flv-mov-3gp-mp3-
                MP4-AVI-FLV-MOV-3GP-MP3`;
            }
            if (checkType.indexOf(fileType) === -1) {
                //报错
                //提示出错
                this.fileTip = true;
                switch (uploadType) {
                case 'IMAGE' :
                    this.msg = this.$t('lab_file_tips_6');
                    break;
                case 'DOCUMENT' :
                    this.msg = this.$t('lab_file_tips_11');
                    break;
                case 'VEDIO' :
                    this.msg = this.$t('lab_file_tips_12');
                    break;
                case 'FILES' :
                    this.msg = this.$t('lab_file_tips_14');
                    break;
                }
                setTimeout(() => {
                    this.fileTip = false;
                }, 3000);
                return false;
            }
            return true;
        },
        shareUpFile(event) { //上传文件
            if (!this.validataFile(event.target.value, this.$route.query.type)) {
                return;
            };
            this.uploading = true;
            let param = new FormData(); // 创建form对象
            let files = event.target.files[0];
            param.append('file', files); // 通过append向form对象添加数据
            let config = {
                headers: {'Content-Type': 'multipart/form-data'}
            }; // 添加请求头
            this.$axios.post(`/app/api/file`, param, config).then(response => {
                this.uploading = false;
                if (response.data.message === 'SUCCESS') {
                    let fileData = {
                        attachmentType: '',
                        fileName: files.name.substring(0, files.name.lastIndexOf('.')),
                        id: 0,
                        orignalFileName: files.name,
                        url: response.data.url
                    };
                    if (this.$route.query.type === 'IMAGE') {
                        this.upFiles.push(fileData);
                    } else {
                        this.$set(this.upFiles, 0, fileData);
                    }
                }
            });
            // let fromData = new FormData();
            // fromData.append('file', event.target.files[0]);
            // this.$axios({
            //     method: 'POST',
            //     url: '/app/kb/attachment/uploadMobile',
            //     headers: {'Content-Type': 'multipart/form-data'},
            //     data: fromData
            // }).then(res => {
            //     this.uploading = false;
            //     if (this.$route.query.type === 'IMAGE') {
            //         this.upFiles.push(res.data.result.attachment);
            //     } else {
            //         this.$set(this.upFiles, 0, res.data.result.attachment);
            //     }
            // });
        },
        deleteUpFile(index, id) {
            // this.$axios({
            //     method: 'POST',
            //     url: `/app/kb/attachment/delete/${id}`
            // }).then(res => {
            //     this.upFiles.splice(index, 1);
            // });
            this.upFiles.splice(index, 1);
        },
        beforeSave() {
            this.$toast(this.$t('mandatory_fields_fill_in'));
        },
        countWord(value) {
            let sum = 0;
            for (let i = 0; i < value.length; i++) {
                if (/[\u4e00-\u9fa5]/.test(value[i])) {
                    sum = sum + 2;
                } else {
                    sum = sum + 1;
                }
            }
            return sum;
        },
        countWordTips(text, limitNum) {
            // 插入的图片算一个字符
            let strTemValue = text.replace(/<(?:img|embed).*?>/gi, 'K').replace(/\r\n|\n|\r|\t|\s/gi, '');
            // 去掉html标签
            let strValue = strTemValue.replace(/<[^>]*>/g, '');
            const count = this.countWord(strValue);
            if (limitNum >= count) { // 没有超过限定字数
                return true;
            }
            return false;
        },
        save() {
            if (this.content) {
                let countNumFlag = this.countWordTips(this.content, 2000);
                if (!countNumFlag) {
                    this.$toast(this.$t('content_limite_num', {value1: this.$t('cos_contents'), value2: 2000}));
                    return false;
                }
            }
            let data = {
                kbiTitle: this.kbi_title,
                kbiContent: this.$route.query.type === 'ARTICLE' ? this.content ? process.env.NODE_ENV === 'production_app' ? this.handleContent : this.content : '' : '',
                kicKbcId: this.selectCatalog.kbcId,
                sourceType: 0,
                kbiDocumentSourceType: this.kbiDocumentSourceType,
                kbiDownload: this.isDown ? 1 : 0,
                kbiAccessType: this.kbiAccessType,
                kbiEditType: this.kbiEditType,
                kbiStatus: 'ON',
                documentType: this.$route.query.type === 'ARTICLE' ? 1 : 2,
                kbiType: this.$route.query.type === 'FILES' ? 'DOCUMENT' : this.$route.query.type,
                kbiImage: '/imglib/knowledge/h1/kc_a_01.jpg'
            };
            if (this.kbiDocumentSourceUrl && this.kbiDocumentSourceUrl.length > 0) {
                data.kbiDocumentSourceUrl = this.kbiDocumentSourceUrl;
            }
            if (this.kbiAccessType === 1 && this.kbiAccessPersonnelIds.length > 0) {
                // let ids = [];
                // this.kbiAccessPersonnelIds.forEach((i) => {
                //     ids.push(i.usr_ent_id);
                // });
                data.kbiAccessPersonnelIds = this.kbiAccessPersonnelIds;
            }
            if (this.kbiEditType === 0 && this.kbiEditPersonnelIds.length > 0) {
                // let ids = [];
                // this.kbiEditPersonnelIds.forEach((i) => {
                //     ids.push(i.usr_ent_id);
                // });
                data.kbiEditPersonnelIds = this.kbiEditPersonnelIds;
            }
            if (this.$route.query.type === 'DOCUMENT' || this.$route.query.type === 'FILES') {
                data.attachments = this.upFiles;
            }
            this.$axios.post(`/app/api/trainee/kb/item/save`, data).then(res => {
                this.$toast(this.$t('share_approve_tip'));
                setTimeout(() => {
                    this.$router.replace({path: '/learn/knowledge'});
                }, 3000);
            });
        },
        classificationSave() { //分类保存
            this.tagToggle = false;
            this.selectCatalog = this.tempSelectCatalog;
        },
        labelSave() {
            this.tagToggle = false;
            this.labelList = this.tagsSelected;
        },
        findClassCatalog() {
            // 获取知识目录分类--一次性
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/kb/item/list/tree`,
                params: {
                    kbcTcrId: 0
                }
            }).then((res) => {
                if (res.data) {
                    this.getClassifyList = this.backData(res.data);
                }
            });
        },
        /**
         * 分类弹窗
         * */
        mlChange(val) {
            let lastI = val.selectedOptions.length - 1;
            let lastChild = val.selectedOptions[lastI];
            this.selectCatalog = {
                kbcId: val.value,
                kbcTitle: lastChild.name
            };
            this.cascaderValue = val.value;
        },
        /**
         * 递归处理分类数据
         * */
        /**
     * 递归处理回显
     * */
        backData(list) {
            const arr = list;
            if (arr && arr.length > 0) {
                arr.forEach((item, index) => {
                    // 是否过滤未发布
                    if (this.ishideUnpublish) {
                        if (item.kbcStatus !== 'ON') {
                            arr.splice(index, 1);
                        }
                    }
                    if (item.children && item.children.length > 0) {
                        this.backData(item.children);
                    }
                });
            }
            return arr;
        }
    },
    mounted() {
        this.shareType = this.$route.query.type;
        switch (this.shareType) {
        case 'IMAGE':
            this.shareType = this.$t('pictures'); //图片
            break;
        case 'VEDIO':
            this.shareType = this.$t('video'); //视频
            break;
        case 'ARTICLE':
            this.shareType = this.$t('article'); //文章
            break;
        case 'DOCUMENT':
            this.shareType = this.$t('document'); //文档
            break;
        case 'FILES':
            this.shareType = this.$t('FILES'); //文件
            break;
        };
        //分类
        this.findClassCatalog();
        //标签
        // this.$axios({
        //     method: 'POST',
        //     url: '/app/kb/tag/admin/getTagJson'
        // }).then((res) => {
        //     this.getTagList = res.data;
        // });
    },
    filters: {
        omit(val, type) {
            if (val) {
                let nameString = val.substr(0, val.lastIndexOf('.'));
                if (nameString.length > 13) {
                    nameString = `${nameString.substr(0, 7)}...${nameString.substr(-5)}`;
                }
                return `${nameString}.${type}`;
            } else {
                return val;
            }
        }
    },
    created() {
        this.$Validator.extend('tipsTitle', {
            validate(value) {
                let num = 0;
                for (let i = 0; i < value.length; i++) {
                    if (value.charCodeAt(i) > 127 || value.charCodeAt(i) === 94) {
                        num += 2;
                    } else {
                        num += 1;
                    }
                }
                if (num > 80) {
                    return false;
                } else {
                    return true;
                }
            }
        });
        this.$Validator.extend('tipsDetail', {
            validate(value) {
                let num = 0;
                for (let i = 0; i < value.length; i++) {
                    if (value.charCodeAt(i) > 127 || value.charCodeAt(i) === 94) {
                        num += 2;
                    } else {
                        num += 1;
                    }
                }
                if (num > 400) {
                    return false;
                } else {
                    return true;
                }
            }
        });
        this.$Validator.extend('tipsContent', {
            validate(value) {
                let num = 0;
                for (let i = 0; i < value.length; i++) {
                    if (value.charCodeAt(i) > 127 || value.charCodeAt(i) === 94) {
                        num += 2;
                    } else {
                        num += 1;
                    }
                }
                if (num > 20000) {
                    return false;
                } else {
                    return true;
                }
            }
        });
    },
    watch: {
        upFiles() {
            this.$nextTick(() => {
                this.$previewRefresh();
            });
        },
        isAccess() {
            if (!this.isAccess) {
                this.tagToggle = false;
            }
        },
        isEdit() {
            if (!this.isEdit) {
                this.tagToggle = false;
            }
        },
        kbiAccessPersonnelIds() {
            if (this.kbiAccessPersonnelIds && this.kbiAccessPersonnelIds.length > 0) {
                this.kbiAccessType = 1;
            }
        },
        kbiEditPersonnelIds() {
            if (this.kbiEditPersonnelIds && this.kbiEditPersonnelIds.length > 0) {
                this.kbiEditType = 0;
            }
        },
        kbiAccessType() {
            if (this.kbiAccessType !== 1) {
                this.kbiAccessPersonnelIds = [];
            }
        },
        kbiEditType() {
            if (this.kbiEditType !== 0) {
                this.kbiEditPersonnelIds = [];
            }
        }
    }
};
</script>

<style scoped lang='less'>
    .catalog-select {
        background: #075ebb;
        color: #fff;
    }
    .module-list-10 li {
        height: 60px;
        line-height: 60px;
        border-bottom: 1px solid #e6e6e6;
        background: #ffffff;
        padding: 0 15px;
    }
    .module-list-10 li:nth-last-child(1) {
        border-bottom: none;
    }
    .arrow-right {
        margin: 25px 0 0 0;
    }
    .popup-box {
        position: absolute;
        top: 0;
        z-index: 101;
        width: 100%;
        height: 100%;
        padding: 0;
        background: #ffffff;
    }
    .catalog:checked + label{
        background: #075ebb;
        color: #ffffff;
    }
    .word-title-08 {
        float: right;
        margin-right: 5px;
        max-width: 130px;
        overflow: hidden;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    /deep/ .ql-container {
        height: 260px;
    }
    .write-btn-right{
        position: absolute;
        right: 13px;
    }
</style>
